package com.zl.learning.json.gson;

import com.google.gson.*;

import java.lang.reflect.Type;

public class UserJsonDeserializer implements JsonDeserializer<User> {
    Gson gson = new Gson();

    @Override
    public User deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        User<ClassRoom> user = gson.fromJson(jsonElement,User.class);
        if (jsonObject.get("userId") != null) {
            user.setId(jsonObject.get("userId").getAsInt());
        }
        if (jsonObject.get("userName") != null) {
            user.setName(jsonObject.get("userName").getAsString());
        }
        if (jsonObject.get("userPassword") != null) {
            user.setPasswd(jsonObject.get("userPassword").getAsString());
        }
        if (jsonObject.get("ClassRoom") != null) {
            ClassRoom classRoom = gson.fromJson(jsonObject.get("ClassRoom"), ClassRoom.class);
            user.setClassRoom(classRoom);
        }
        return user;
    }
}
